package com.ujiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ujiuye.config.*;
import com.ujiuye.mapper.*;
import com.ujiuye.pojo.Member;
import com.ujiuye.pojo.Order;
import com.ujiuye.pojo.Ordersetting;
import com.ujiuye.pojo.Setmeal;
import com.ujiuye.service.IOrderService;
import com.ujiuye.vo.BusinessVo;
import com.ujiuye.vo.OrderVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单-会员下单预约检查 服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-07-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrdersettingMapper ordersettingMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SetmealMapper setmealMapper;

    /**
     * 1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行 预约
     * 2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
     * 3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
     * 4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注 册并进行预约
     * 5、预约成功，更新当日的已预约人数
     * @param map
     * @return
     */

    @Override
    public Result saveOrder(Map<String, Object> map) {
        //先判断这个日期是否可以预约
        QueryWrapper<Ordersetting> ordersettingQueryWrapper = new QueryWrapper<>();
        //通过预约的时间来判断是否可以预约
        ordersettingQueryWrapper.eq("orderDate",(String)map.get("orderDate"));
        Ordersetting ordersetting = ordersettingMapper.selectOne(ordersettingQueryWrapper);
        if (ordersetting==null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断查回来的ordersetting的预约数和可预约数是否相等（判断预约是否满了）
        if (ordersetting.getReservations()>=ordersetting.getNumber()){
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //判断是否有这个会员通过身份证和电话来判断是否有这个会员
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("idCard",map.get("idCard"));
        memberQueryWrapper.eq("phoneNumber",map.get("telephone"));
        Member inMember = memberMapper.selectOne(memberQueryWrapper);
        //没有这个会员
        if (inMember==null){
            //添加会员
            inMember = new Member();
            String sex = Integer.parseInt((String) map.get("sex"))==1 ? "男" : "女";
            inMember.setSex(sex);
            inMember.setBirthday(getBirthday((String) map.get("idCard")));
            inMember.setName((String) map.get("name"));
            inMember.setPhonenumber((String) map.get("telephone"));
            inMember.setIdcard((String) map.get("idCard"));
            inMember.setPassword("123456");
            inMember.setRegtime(LocalDate.now());
            memberMapper.insert(inMember);
        }
        //在通过id 和 预约时间和 套餐id判断是否已经预约过这个套餐
        Integer inMemberId = inMember.getId();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("member_id",inMemberId);
        orderQueryWrapper.eq("orderDate",(String)map.get("orderDate"));
        orderQueryWrapper.eq("setmeal_id",map.get("setmealId"));
        Order sysOrder = orderMapper.selectOne(orderQueryWrapper);
        //预约了这个套餐
        if (sysOrder!=null){
            return new Result(false,MessageConstant.HAS_ORDERED);
        }
        //没有预约这个套餐，添加这个套餐
        Order order1  = new Order();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate orderDate = LocalDate.parse((String) map.get("orderDate"), fmt);
        order1.setOrderdate(orderDate);
        order1.setOrderstatus("未到诊");
        order1.setSetmealId(Integer.parseInt((String)map.get("setmealId")));
        order1.setMemberId(inMemberId);
        order1.setOrdertype("微信预约");
        orderMapper.insert(order1);
        //更新预约人数
        ordersetting.setReservations(ordersetting.getReservations()+1);
        ordersettingMapper.updateById(ordersetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }


    public LocalDate getBirthday(String IDcard) {
        String year = IDcard.substring(6, 10);
        String month = IDcard.substring(10,12);
        String day = IDcard.substring(12,14);
        String birthday = year+"/"+month+"/"+day;
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        return LocalDate.parse(birthday,fmt);
    }


    @Override
    public BusinessVo getBusinessVo() {
        BusinessVo businessVo = new BusinessVo();
        businessVo.setTodayNewMember(todayNewMember());//本日新增会员数
        businessVo.setTotalMember(totalMember());//总会员数
        businessVo.setThisWeekNewMember(thisWeekNewMember());
        businessVo.setThisMonthNewMember(thisMonthNewMember());//本月新增会员数
        businessVo.setTodayOrderNumber(todayOrderNumber());//今日预约数
        businessVo.setTodayVisitsNumber(todayVisitsNumber());//今日到诊数
        businessVo.setThisWeekOrderNumber(thisWeekOrderNumber());//本周预约数
        businessVo.setThisWeekVisitsNumber(thisWeekVisitsNumber());//本周到诊数
        businessVo.setThisMonthOrderNumber(thisMonthOrderNumber());//本月预约数
        businessVo.setThisMonthVisitsNumber(thisMonthVisitsNumber());//本月到诊数
        businessVo.setHotSetmeal(hotSetmeal());

        return businessVo;
    }

    @Override
    public PageResult todayOrderList(QueryPageBean queryPageBean) throws Exception {
        String date2String = DateUtils.parseDate2String(new Date());
        Page<Order> page = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderDate",date2String);
        Page<Order> orderPage = orderMapper.selectPage(page, orderQueryWrapper);
        List<Order> orderList = orderPage.getRecords();
        List<OrderVo> orderVoList = new ArrayList<>();
//        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
//        if (queryString!=null && queryString.length()>0){
//            memberQueryWrapper.eq("phoneNumber",queryString);
//            Member member = memberMapper.selectOne(memberQueryWrapper);
//            QueryWrapper<Order> orderQueryWrapper1 = new QueryWrapper<>();
//            orderQueryWrapper1.eq("member_id",member.getId());
//            orderQueryWrapper1.eq("orderDate",date2String);
//            Order order = orderMapper.selectOne(orderQueryWrapper1);
//            QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
//            setmealQueryWrapper.eq("id",order.getSetmealId());
//            Setmeal setmeal = setmealMapper.selectOne(setmealQueryWrapper);
//            OrderVo orderVo = new OrderVo(setmeal.getName(),member.getName(),order.getOrderdate(),member.getIdcard(),member.getPhonenumber());
//            orderVoList.add(orderVo);
//            int size = orderVoList.size();
//            return new PageResult((long) size,orderVoList);
//        }
        for (Order order : orderList) {
            QueryWrapper<Member> memberQueryWrapper1 = new QueryWrapper<>();
            memberQueryWrapper1.eq("id",order.getMemberId());
            Member member = memberMapper.selectOne(memberQueryWrapper1);
            QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
            setmealQueryWrapper.eq("id",order.getSetmealId());
            Setmeal setmeal = setmealMapper.selectOne(setmealQueryWrapper);
            OrderVo orderVo = new OrderVo(setmeal.getName(),member.getName(),order.getOrderdate(),member.getIdcard(),member.getPhonenumber(),order.getOrderstatus());
            orderVoList.add(orderVo);
        }
        List<OrderVo> queryList = new ArrayList<>();
        if (queryString!=null && queryString.length()>0){
            for (OrderVo orderVo : orderVoList) {
                if (orderVo.getPhoneNumber().equals(queryString)){
                    queryList.add(orderVo);
                }
            }
            return new PageResult((long)queryList.size(),queryList);
        }
        return new PageResult(orderPage.getTotal(),orderVoList);
    }

    @Override
    public PageResult toWeekOrderList(QueryPageBean queryPageBean) {
        Date thisWeekMonday = DateUtils.getThisWeekMonday();
        Page<Order> page = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",thisWeekMonday);
        Page<Order> orderPage = orderMapper.selectPage(page, orderQueryWrapper);
        List<Order> orderList = orderPage.getRecords();
        List<OrderVo> orderVoList = new ArrayList<>();
        for (Order order : orderList) {
            QueryWrapper<Member> memberQueryWrapper1 = new QueryWrapper<>();
            memberQueryWrapper1.eq("id",order.getMemberId());
            Member member = memberMapper.selectOne(memberQueryWrapper1);
            QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
            setmealQueryWrapper.eq("id",order.getSetmealId());
            Setmeal setmeal = setmealMapper.selectOne(setmealQueryWrapper);
            OrderVo orderVo = new OrderVo(setmeal.getName(),member.getName(),order.getOrderdate(),member.getIdcard(),member.getPhonenumber(),order.getOrderstatus());
            orderVoList.add(orderVo);
        }
        List<OrderVo> queryList = new ArrayList<>();
        if (queryString!=null && queryString.length()>0){
            for (OrderVo orderVo : orderVoList) {
                if (orderVo.getPhoneNumber().equals(queryString)){
                    queryList.add(orderVo);
                }
            }
            return new PageResult((long)queryList.size(),queryList);
        }
        return new PageResult(orderPage.getTotal(),orderVoList);
    }




    @Override
    public PageResult toMothOrderList(QueryPageBean queryPageBean) {
        Date firstDay4ThisMonth = DateUtils.getFirstDay4ThisMonth();
        Page<Order> page = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",firstDay4ThisMonth);
        Page<Order> orderPage = orderMapper.selectPage(page, orderQueryWrapper);
        List<Order> orderList = orderPage.getRecords();
        List<OrderVo> orderVoList = new ArrayList<>();
        for (Order order : orderList) {
            QueryWrapper<Member> memberQueryWrapper1 = new QueryWrapper<>();
            memberQueryWrapper1.eq("id",order.getMemberId());
            Member member = memberMapper.selectOne(memberQueryWrapper1);
            QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
            setmealQueryWrapper.eq("id",order.getSetmealId());
            Setmeal setmeal = setmealMapper.selectOne(setmealQueryWrapper);
            OrderVo orderVo = new OrderVo(setmeal.getName(),member.getName(),order.getOrderdate(),member.getIdcard(),member.getPhonenumber(),order.getOrderstatus());
            orderVoList.add(orderVo);
        }
        List<OrderVo> queryList = new ArrayList<>();
        if (queryString!=null && queryString.length()>0){
            for (OrderVo orderVo : orderVoList) {
                if (orderVo.getPhoneNumber().equals(queryString)){
                    queryList.add(orderVo);
                }
            }
            return new PageResult((long)queryList.size(),queryList);
        }
        return new PageResult(orderPage.getTotal(),orderVoList);

    }


    //本日新增会员数
    private Integer todayNewMember(){
        int count=0;
        try {
            String date2String = DateUtils.parseDate2String(new Date());
            QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("regTime",date2String);
            count = memberMapper.selectCount(memberQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    };
    //总会员数
    private Integer totalMember(){
        Integer count = memberMapper.selectCount(null);
        return count;
    };
    //本周新增会员数
    private Integer thisWeekNewMember(){
        Date thisWeekMonday = DateUtils.getThisWeekMonday();
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.ge("regTime",thisWeekMonday);
        Integer count = memberMapper.selectCount(memberQueryWrapper);
        return count;
    };
    //本月新增会员数
    private Integer thisMonthNewMember(){
        Date firstDay4ThisMonth = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.ge("regTime",firstDay4ThisMonth);
        Integer count = memberMapper.selectCount(memberQueryWrapper);
        return count;
    };
    //今日预约数
    private Integer todayOrderNumber(){
        int count=0;
        try {
            String date2String = DateUtils.parseDate2String(new Date());
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("orderDate",date2String);
            count = orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;

    };
    //今日到诊数
    private Integer todayVisitsNumber(){
        int count=0;
        try {
            String date2String = DateUtils.parseDate2String(new Date());
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("orderDate",date2String);
            orderQueryWrapper.eq("orderStatus","已到诊");
            count = orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    };
    //本周预约数
    private Integer thisWeekOrderNumber(){
        Date thisWeekMonday = DateUtils.getThisWeekMonday();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",thisWeekMonday);
        Integer count = orderMapper.selectCount(orderQueryWrapper);
        return count;

    };
    //本周到诊数
    private Integer thisWeekVisitsNumber(){
        Date thisWeekMonday = DateUtils.getThisWeekMonday();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",thisWeekMonday);
        orderQueryWrapper.eq("orderStatus","已到诊");
        Integer count = orderMapper.selectCount(orderQueryWrapper);
        return count;

    };
    //本月预约数
    private Integer thisMonthOrderNumber(){
        Date firstDay4ThisMonth = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",firstDay4ThisMonth);
        Integer count =orderMapper.selectCount(orderQueryWrapper);
        return count;
    };
    //本月到诊数
    private Integer thisMonthVisitsNumber(){
        Date firstDay4ThisMonth = DateUtils.getFirstDay4ThisMonth();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.ge("orderDate",firstDay4ThisMonth);
        orderQueryWrapper.eq("orderStatus","已到诊");
        Integer count =orderMapper.selectCount(orderQueryWrapper);
        return count;

    };
    private List<Map<String,Object>> hotSetmeal(){
        List<Map<String, Object>> businessVo = setmealMapper.getBusinessVo();
        return businessVo;
    };

}
